package cn.iocoder.yudao.module.contract.utils;

import com.alibaba.excel.util.FileUtils;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.awt.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileDownloadUtil {
    public static ResponseEntity<?> downloadFile(String fileUrl,String fileName) {
        try {
            File file = new File(fileUrl);
            String extension = file.getName().substring(file.getName().lastIndexOf("."));
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new RuntimeException("Failed to retrieve file: " + responseCode);
            }

            InputStream inputStream = connection.getInputStream();

            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header("Access-Control-Expose-Headers", "Content-Disposition,download-filename")
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName+extension + "\"")
                    .header("download-filename", fileName+extension )
                    .body(new InputStreamResource(inputStream));
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    public static ResponseEntity<?> downloadZip(List<String> fileUrls,List<String> fileNames) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);

            for (int i = 0; i < fileUrls.size(); i++) {
                String fileUrl = fileUrls.get(i);
                String fileName = fileNames.get(i);
                File file = new File(fileUrl);
                String extension = file.getName().substring(file.getName().lastIndexOf("."));
                // 下载文件并添加到ZIP中
                InputStream inputStream = downloadFileFromUrl(fileUrl);
                if (inputStream != null) {
                    addFileToZip(zipOutputStream, inputStream, fileName+extension);
                    inputStream.close();
                }
            }

            zipOutputStream.close();
            byte[] zipBytes = byteArrayOutputStream.toByteArray();
            ByteArrayResource resource = new ByteArrayResource(zipBytes);

            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header("Access-Control-Expose-Headers", "Content-Disposition,download-filename")
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+new Date().getTime()+".zip")
                    .header("download-filename", new Date().getTime()+".zip" )
                    .body(resource);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    public static ResponseEntity<?> downloadZip(List<String> fileUrls,List<String> fileNames,String zipName) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);

            for (int i = 0; i < fileUrls.size(); i++) {
                String fileUrl = fileUrls.get(i);
                String fileName = fileNames.get(i);
                File file = new File(fileUrl);
                String extension = file.getName().substring(file.getName().lastIndexOf("."));
                // 下载文件并添加到ZIP中
                InputStream inputStream = downloadFileFromUrl(fileUrl);
                if (inputStream != null) {
                    addFileToZip(zipOutputStream, inputStream, fileName+extension);
                    inputStream.close();
                }
            }

            zipOutputStream.close();
            byte[] zipBytes = byteArrayOutputStream.toByteArray();
            ByteArrayResource resource = new ByteArrayResource(zipBytes);

            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header("Access-Control-Expose-Headers", "Content-Disposition,download-filename")
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+ URLEncoder.encode(zipName,"UTF-8")+".zip")
                    .header("download-filename", URLEncoder.encode(zipName,"UTF-8")+".zip" )
                    .body(resource);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    private static InputStream downloadFileFromUrl(String fileUrl) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException("Failed to retrieve file from URL: " + fileUrl);
        }

        return connection.getInputStream();
    }

    private static void addFileToZip(ZipOutputStream zipOutputStream, InputStream inputStream, String fileName) throws IOException {
        ZipEntry zipEntry = new ZipEntry(fileName);
        zipOutputStream.putNextEntry(zipEntry);

        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) > 0) {
            zipOutputStream.write(buffer, 0, len);
        }

        zipOutputStream.closeEntry();
    }

    public static void main(String[] args) {
//        String filePath = "D:\\Download\\TEST002.docx";
//        String content = readWordDocument(filePath);
//        writeToFile(content, "temp.txt");
        printFile("D:\\Download\\TEST002.docx");
    }
    public static void printFile(String filePath) {
        try {
            Desktop desktop = Desktop.getDesktop();
            File file = new File(filePath);
            desktop.print(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void writeToFile(String content, String filePath) {
        try {
            FileWriter writer = new FileWriter(filePath);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static String readWordDocument(String filePath) {
        try {
            FileInputStream fis = new FileInputStream(filePath);
            XWPFDocument document = new XWPFDocument(fis);
            XWPFWordExtractor extractor = new XWPFWordExtractor(document);
            String text = extractor.getText();
            fis.close();
            return text;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
